package main

import (
	"context"
	"encoding/json"
	"enotify/internal/xys/notify"
	"fmt"
	"github.com/BurntSushi/toml"
	"golang.org/x/sync/errgroup"
	"log"
	"net/http"
	"os"
	"os/signal"
	"strconv"
	"syscall"
)

func main()  {
	conf := notify.Config{}
	_, err := toml.DecodeFile("./conf.toml",&conf)
	if err != nil {
		panic(err)
	}
	log.Printf("conf(%+v),group(%+v),provider(%+v),redis(%+v) \n",conf,conf.Group,conf.Provider,conf.Redis)

	service := notify.NewNotify(&conf)
	c := make(chan os.Signal, 1)
	ctx,cancel  := context.WithCancel(context.Background())
	gp := new(errgroup.Group)
	gp.Go(func() error {
		return service.Start()
	})
	gp.Go(httpServer(ctx,service))
	if err := gp.Wait(); err != nil {
		panic(err)
		cancel()
	}
	signal.Notify(c, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT)
	for {
		select {
		case <-c:
			cancel()
			service.Stop()
			return
		case <-ctx.Done():
			service.Stop()
			return
		}
	}

}
type GroupInfo struct {
	Id int `json:"id"`
	SceneId int `json:"scene_id"`
	FileName string `json:"file_name"`
}
func httpServer(ctx context.Context,nt *notify.Notify) func() error {
	return func() error {
		mux := http.NewServeMux()
		mux.HandleFunc("/stop", func(resp http.ResponseWriter, req *http.Request){
			values := req.URL.Query()
			id := values.Get("id")
			groupId,err := strconv.Atoi(id)
			if err != nil || groupId<1 {
				fmt.Fprintln(resp, "参数错误")
				return
			}
			if nt.StopGroup(int64(groupId)) {
				fmt.Fprintln(resp, "停止成功")
			} else {
				fmt.Fprintln(resp, "停止失败")
			}

		})
		mux.HandleFunc("/restart",func(resp http.ResponseWriter, req *http.Request){
			values := req.URL.Query()
			id := values.Get("id")
			groupId,err := strconv.Atoi(id)
			if err != nil || groupId<1 {
				fmt.Fprintln(resp, "参数错误")
				return
			}
			key := fmt.Sprintf("notify:group:%d:info",groupId)
			result,err := nt.GetKeyVal(key)
			if err != nil {
				fmt.Fprintln(resp, err.Error())
			}
			ginfo := GroupInfo{}
			err = json.Unmarshal([]byte(result),&ginfo)
			if err != nil {
				fmt.Fprintln(resp, "json参数错误")
			}
			if ginfo.Id<1 || ginfo.SceneId<1 || ginfo.FileName == "" {
				fmt.Fprintln(resp, "json参数错误2")
			}
			fmt.Fprintln(resp,"restart ok")
			greq := notify.GroupReq{
				Id:      int64(ginfo.Id),
				SceneId: int64(ginfo.SceneId),
				SyncPrgFun: notify.SyncPrgToMQ("TEST"),
				LoadUserFun:     notify.LoadUserInfoFromCsvFile(notify.CsvConfig{
					Dir:       ginfo.FileName,
					AppPos:    1,
					MobilePos: 2,
					OpenIdPos: 3,
					StartRow:  1,
				}),
				Req:     nil,
			}
			log.Printf("%v",greq)
			err = nt.Push(greq)
			if err != nil {
				fmt.Fprintln(resp, err.Error())
			}
		})
		mux.HandleFunc("/push", func(resp http.ResponseWriter, req *http.Request) {
			values := req.URL.Query()
			id := values.Get("id")
			groupId,err := strconv.Atoi(id)
			if err != nil {
				fmt.Fprintln(resp, "参数错误")
				return
			}
			sid := values.Get("sceneId")
			sceneId,err := strconv.Atoi(sid)
			if err != nil {
				fmt.Fprintln(resp, "参数错误")
				return
			}
			fileName := values.Get("fileName")
			if fileName == ""{
				fmt.Fprintln(resp, "文件参数错误")
				return
			}
			_, err = os.Stat(fileName)
			if err != nil {
				fmt.Fprintln(resp, fileName,"不存在")
				return
			}

			greq := notify.GroupReq{
				Id:      int64(groupId),
				SceneId: int64(sceneId),
				SyncPrgFun: notify.SyncPrgToMQ("TEST"),
				LoadUserFun:     notify.LoadUserInfoFromCsvFile(notify.CsvConfig{
					Dir:       fileName,
					AppPos:    1,
					MobilePos: 2,
					OpenIdPos: 3,
					StartRow:  1,
				}),
				Req:     nil,
			}

			log.Printf("%v",greq)
			err = nt.Push(greq)
			if err != nil {
				fmt.Fprintln(resp, err.Error())
			}
			gInfo := GroupInfo{
				Id:       groupId,
				SceneId:  sceneId,
				FileName: fileName,
			}
			key := fmt.Sprintf("notify:group:%d:info",groupId)
			json,_:= json.Marshal(gInfo)
			err = nt.SetKeyVal(key,string(json))
			if err != nil {
				fmt.Fprintln(resp,err.Error())
			}
		})

		server := &http.Server{
			Addr:    "127.0.0.1:8001",
			Handler: mux,
		}
		go func() {
			select {
			case <-ctx.Done():
				fmt.Println("close1")
				server.Shutdown(ctx)
			}
		}()
		log.Printf("start http server(%s)","127.0.0.1:8001")
		err := server.ListenAndServe()
		return err
	}

}